package com.share.example.json2flat.listener;

import com.share.example.json2flat.constants.ConfConstant;
import com.share.example.json2flat.service.HbaseService;
import com.share.example.json2flat.service.IMappingConfService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class TopicListener {
    @Autowired
    private HbaseService hbaseService;

    @Autowired
    private IMappingConfService mappingConfService;

    //格式化数据,为标准格式
    @KafkaListener(topics = {"#{'${kafka.topics}'.split(',')}"})
    public void formatData(ConsumerRecord<Object, Object> record, Acknowledgment ack) {
        //1.业务处理
        try {
            log.info("kafka消费消息,topic={},partition={},offset={},value={}", record.topic(), record.partition(), record.offset(), record.value());
            mappingConfService.flatDataAndToKafka(record.value());
        } catch (Exception e) {
            log.error("kafka消费异常", e);
        }

        //2.提交偏移量
        ack.acknowledge();
    }


    //消费数据刷新到hbase
    @KafkaListener(topics = {ConfConstant.TOPIC_FLAT_JSON})
    public void consumerTopicToHbase(ConsumerRecord<Object, Object> record, Acknowledgment ack) {
        //1.业务处理
        try {
            log.info("kafka消费消息,topic={},partition={},offset={},value={}", record.topic(), record.partition(), record.offset(), record.value());
            hbaseService.save(record.value());
        } catch (Exception e) {
            log.error("kafka消费异常", e);
        }

        //2.提交偏移量
        ack.acknowledge();
    }
}
